<?php

namespace app\admin\controller;

use think\exception\ValidateException;
use app\model\Points;

class PointsController extends Base
{

	function index()
	{
		$weid = weid();
		$keyword = input('post.keyword', '', 'serach_in');
		$prefix = input('post.prefix');
		$type = input('post.type');
		$query = Points::where(['p.weid' => $weid])->alias('p')->leftJoin('member m', 'm.id = p.uid');
		$query->with(['member']);
		if(!empty($prefix)){
			$query->where('p.prefix', $prefix);
		}
		if (!empty($type)) {
			$query->where('p.type', $type);
		}
		if (!empty($keyword)) {
			$query->where('p.order_num_alias|p.description|m.nickname|m.mobile', 'like', '%' . $keyword . '%');
		}

		$res = $query->field('p.*')->order('p.id desc')
			->paginate(getpage())
			->toArray();
		foreach ($res['data'] as $k => &$v) {
			$v['creat_time'] = date('Y-m-d H:i:s', $v['creat_time']);
			if ($v['prefix'] == 1) {
                $v['prefix'] = '增加';
            } elseif ($v['prefix'] == 2) {
                $v['prefix'] = '减少';
            }else{
				$v['prefix'] = '未知';
			}
			if ($v['type'] == 1) {
                $v['type'] = '用户';
            } elseif ($v['type'] == 2) {
                $v['type'] = '管理员';
            }else{
				$v['type'] = '未知';
			}
		}
		unset($v);
		$data['data'] = $res;

		return $this->json($data);
	}

	function getInfo()
	{
		$id =  $this->request->post('id', '', 'serach_in');
		if (!$id) throw new ValidateException('参数错误');

		$data = Points::where(['id'=>$id])->with('member')->find();
		if (!empty($data)) {
			$data = $data->toArray();
			$data['image'] = json_decode($data['image'], true);
			$data['create_time'] = date('Y-m-d H:i:s', $data['create_time']);
		}

		return $this->json(['data' => $data]);
	}
	function listUpdate()
	{
		$data = only('id,status,sort');
		if (!$data['id']) throw new ValidateException('参数错误');
		Points::update($data);

		return $this->json(['msg' => '操作成功']);
	}
	// 处理售后订单
	public function refundhandle()
	{
		$postdata = input('post.');
		try {
			$postdata['OrderRefund']['response_time'] = time();

			$r = OrderRefund::where('id', $postdata['OrderRefund']['id'])->update($postdata['OrderRefund']);
			if ($r && $postdata['OrderRefund']['refund_status'] == 1) {
				$r = Order::refund_order($postdata);
			}
		} catch (\Exception $e) {
			throw new ValidateException($e->getMessage());
		}

		if ($r) {
			return $this->json(['msg' => '处理成功！']);
		} else {
			throw new ValidateException('处理失败');
		}
	}

	function delete()
	{
		$idx =  $this->request->post('id', '', 'serach_in');
		if (!$idx) throw new ValidateException('参数错误');
		Order::destroy(['id' => explode(',', $idx)], true);
		OrderRefund::where(['order_id' => explode(',', $idx)])->delete();
		return $this->json(['msg' => '操作成功']);
	}
}
